<!DOCTYPE html>
<html lang="en">
<!--js 的终结 https://github.com/cy0707/Learn_JavaScript/issues/16-->
<head>
    <meta charset="UTF-8">
    <title>tab菜单点击切换到对应的内容</title>
    <link rel="stylesheet" type="text/css" href="normalize.css">
    <style>

    </style>
    <script src="jquery-2.1.4.min.js"></script>
    <script>
        function uploadImage(sourceId, targetId) {
            if (typeof FileReader === "undefined") {
                alert("your browser does not support FileReader ... ")
                return
            }
            // console.log("sourceid=" + sourceId)
            // console.log("targetId=" + targetId)
            var reader = new FileReader()
            reader.onload = function (e) {
                $("#" + targetId)[0].src = this.result
            }
            let file = $("#" + sourceId)[0].files[0];
            // console.log(file)
            reader.readAsDataURL(file)
            let data = new FormData($("#" + sourceId)[0])
        }


        function createXHR() {
            if (typeof XMLHttpRequest != 'undefined') {//兼容高版本浏览器
                return new XMLHttpRequest();

            } else if (typeof ActiveXObject != 'undefined') {
                //IE6 采用 ActiveXObject， 兼容IE6
                var versions = [					//由于MSXML库有3个版本，因此都要考虑
                    'MSXML2.XMLHttp.6.0',
                    'MSXML2.XMLHttp.3.0',
                    'MSXML2.XMLHttp'
                ];

                for (var i = 0; i < versions.length; i++) {
                    try {
                        return new ActiveXObject(versions[i]);
                    } catch (e) {
                    }
                }
            } else {
                throw new Error('您的浏览器不支持XHR对象');
            }
        }

        function uploadByXHR(data) {
            var xhr = createXHR();
            xhr.onload = function () {
                if ((xhr.status >= 200 && xhr.status < 300)) {
                    alert(xhr.responseText);
                } else {
                    alert("Request was unsuccessful: " + xhr.status);
                }
            };
            //下载触发
            xhr.addEventListener("progress", function (event) {
                if (event.lengthComputable) {
                    $("#progress").text('Received' + event.position + ' of ' + event.totalSize + 'bytes')
                }
            });
            //上传触发
            xhr.upload.addEventListener("progress", function (event) {
                if (event.lengthComputable) {
                    $("#progress").text('Received' + event.loaded + ' of ' + event.total + 'bytes')
                }
            });
            xhr.open('post', 'http://localhost/upload-file.php', true);
            //有可能会有跨域问题,服务端需要设置
            //php 版本
            // header('Access-Control-Allow-Origin:*');
            // header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
            // header('Access-Control-Allow-Headers:X-Requested-With,Content-Type,Access-Token');
            // header('Access-Control-Max-Age:86400');

            //客户端不用设置
            // xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
            // xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
            // xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            // xhr.setRequestHeader("Content-Type", "multipart/form-data");
            xhr.send(data);
        }

        function uploadByAjax(data) {
            $.ajax({
                url: "http://localhost/upload-file.php",
                type: "POST",
                contentType: false,//必须
                data: data,
                cache: false,
                processData: false,//用于对data参数进行序列化处理 这里必须false
                success: function (result) {
                    $("#result").text(result)
                },
                xhr: function () {
                    let realXhr = createXHR();
                    if (realXhr.upload) {
                        realXhr.upload.addEventListener("progress", function (event) {
                            $("#result").text(event.loaded)
                        })
                    }
                    return realXhr;
                }
            })
        }



        $(document).ready(function () {
            $("#upload-button").click(function (e) {
                let data = new FormData($("form")[0])
                // uploadByXHR(data)
                uploadByAjax(data)
            });

        })


    </script>
</head>
<body>
<div>
    <form id="uploadform" action="http://localhost/upload-file.php" method="post" enctype="multipart/form-data">
        <input id="upload" name="file" type="file" onchange="uploadImage(this.id,'img')">
        <img id="img"
             src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3059607941,393199546&fm=27&gp=0.jpg">
        <input type="submit" value="提交">
    </form>

    <button id="upload-button">上传</button>
    <div>
        <span id="progress"></span>
    </div>
    <div>
        <span id="result"></span>
    </div>

</div>

</body>
</html>